package flect.study;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.reflect.Field;

public class TestDemo {
    public static void main(String[] args) {
        // 目的：尝试使用反射机制，完成保存一个类及其属性信息
        Student student = new Student("张三", 18, "男");
        saveObject(student);
        Teacher teacher = new Teacher("李四", 20, "女", "Java", "尚硅谷");
        saveObject(teacher);
        System.out.println("保存成功！");
    }

    public static void saveObject(Object obj){
        //首先创建一个IO流
        try(
                PrintStream printStream = new PrintStream(
                        new FileOutputStream("flect-study/obj.txt",true))){
            // 首先是获取类对象
            Class c = obj.getClass();
            String simpleName = c.getSimpleName();
            printStream.println("=================="+simpleName+"========================");
            // 获取所有属性
            Field[] fields = c.getDeclaredFields();
            for (Field field : fields) {
                // 获取属性名称
                String name = field.getName();
                // 获取属性的值
                field.setAccessible(true);
                Object o = field.get(obj);
                printStream.println(name+"="+o);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
